import axios from "axios";
import cookie from "js-cookie"
import qs from "qs";
import {ElNotification as notify} from "element-plus";

const client = axios.create();

client.defaults.timeout = 30000;
client.defaults.withCredentials = true;
//instance.defaults.baseURL = 'http://127.0.0.1:8080';
client.defaults.headers['Content-Type'] = 'application/json;charset=UTF-8';
client.defaults.headers['X-Requested-With'] = 'XMLHttpRequest';
client.defaults.transformRequest = [(data, headers) => {
    let tokenType = cookie.get("token_type");
    let accessToken = cookie.get("access_token");
    if (accessToken) {
        headers['Authorization'] = tokenType + ' ' + accessToken;
    }
    if (headers['Content-Type'].indexOf("application/x-www-form-urlencoded") > -1) {
        return qs.stringify(data);
    } else if (headers['Content-Type'].indexOf("application/json") > -1) {
        return JSON.stringify(data);
    } else {
        return data;
    }
}];

client.interceptors.request.use(config => {
    return config;
}, error => {
    return Promise.reject(error);
});

client.interceptors.response.use(response => {
    switch (response.data.status) {
        case 200:
            return response.data;
        case 500:
            notify.error({message: '服务器异常'});
            console.error(response.request.responseURL, JSON.stringify(response.data));
            break;
        default:
            return response.data;
    }
}, error => {
    if (error.response) {
        switch (error.response.status) {
            case 500:
                notify.error({message: '服务器异常'});
                console.error(error.response.request.responseURL, JSON.stringify(error.response.data));
                break;
            case 400:
                break;
            case 401:
                cookie.remove("token_type");
                cookie.remove("access_token");
                cookie.remove("refresh_token");
                localStorage.removeItem("userinfo");
                localStorage.removeItem("defaultActive");
                window.location.href = `/`;
                break;
            case 403:
                break;
            case 302:
                cookie.remove("token_type");
                cookie.remove("access_token");
                cookie.remove("refresh_token");
                localStorage.removeItem("userinfo");
                localStorage.removeItem("defaultActive");
                window.location.href = `/`;
                break
            default:
                return Promise.reject(error);
        }
    } else {
        notify.error({message: '服务器异常'});
        cookie.remove("token_type");
        cookie.remove("access_token");
        cookie.remove("refresh_token");
        localStorage.removeItem("userinfo");
        localStorage.removeItem("defaultActive");
        console.error(error);
        return Promise.reject(error);
    }
});

export default client;

